﻿using System;
using Microsoft.Practices.Unity;
using Sessionizer.Core.Unity;
using Sessionizer.Tests.Abstraction;

namespace Sessionizer.Tests.Unity
{
    public sealed class UnityWrapper : IIoCContainer, IIoCContainerBuilder
    {
        private readonly IUnityContainer _container;

        public UnityWrapper(IUnityContainer container)
        {
            _container = container;
        }

        public static IIoCContainerBuilder Create()
        {
            return new UnityWrapper(new UnityContainer().AddExtension(new SessionLifetimeExtension()));
        }

        public object Resolve(Type type)
        {
            return _container.Resolve(type);
        }

        public IIoCContainerBuilder RegisterType(Type @interface, Type mapping, LifetimeStyle lifetime)
        {
            _container.RegisterType(@interface, mapping, CreateLifetime(lifetime));
            return this;
        }

        public IIoCContainer Build()
        {
            return this;
        }

        private LifetimeManager CreateLifetime(LifetimeStyle style)
        {
            switch (style)
            {
                case LifetimeStyle.Transient:
                    return new TransientLifetimeManager();
                case LifetimeStyle.Session:
                    return new SessionLifetimeManager();
                case LifetimeStyle.Container:
                    return new ContainerControlledLifetimeManager();
                default:
                    throw new ArgumentOutOfRangeException("style");
            }
        }

        public void Dispose()
        {
            _container.Dispose();
        }
    }
}